package com.cookie;

import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SaveCookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) {

		int number = 0;
		Cookie[] cookie = request.getCookies();
		if (cookie != null) {
			for(Cookie c : cookie){
				if("count_key".equals(c.getName())){
					number = Integer.parseInt(c.getValue()) + 1;
				}
			}
		}

		try {
			Cookie cook = new Cookie("count_key",String.valueOf(number));
			
			/*	Set cookie's expiry. 
			 	-	close browse, cookie is failed[default].
			  	0	if the cookie's expiry value is '0' ,now delete
			 		(服务器要删浏览器的cookie，那就再发一个存活期为0的同名cookie给你。) 
			  	+	save the time
			  	------------------------------------------------------------
			  	1.	cookie的大小不要超过4K
			  	2.	对于同一个domain(服务器)，他的cookie的数目不能超过20个
			 */
			cook.setMaxAge(0);
			
			/*	domain__域名	默认是当前服务器的主机(一般都不设置)
			  	path  __路径 	默认是当前Servlet的路径(一般都会设置)
			  	当浏览器访问主机时，只有domain和path都和服务器的一样，那browse就带cookie
			  	(一般path最高，就高到当前应用名)
			  	path_不一定非要是当前路径，子路径都可以的
			 */
			cook.setPath("/cs");
			/**
			 * cookie要注义编码的问题
			 */
			
			response.addCookie(cook);
			PrintWriter out = response.getWriter();
			out.println("<html>");
			out.println("<head><title>Count</title></head>");
			out.println("<body>" +
						"<h1>"+number+"</h1>"+
						"</body>");
			out.println("</html>");
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

}
